<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="80%"
    :before-close="handleClose"
    destroy-on-close
  >
    <!-- 查看模式 -->
    <div v-if="isViewMode">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="avatar-container">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </el-col>
        <el-col :span="12">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="用户昵称">{{
              userInfo.userName
            }}</el-descriptions-item>
            <el-descriptions-item label="账号">{{
              userInfo.account
            }}</el-descriptions-item>
            <el-descriptions-item label="专业">{{
              userInfo.major
            }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{
              userInfo.phone
            }}</el-descriptions-item>
            <el-descriptions-item label="电子邮箱">{{
              userInfo.email
            }}</el-descriptions-item>
            <el-descriptions-item label="账户状态">
              <el-tag :type="userInfo.active ? 'success' : 'danger'">
                {{ userInfo.active ? "已启用" : "已禁用" }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        <el-col :span="24">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="个人简介" label-width="100px">
              {{ userInfo.description || "暂无简介" }}
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </div>

    <!-- 编辑模式 -->
    <el-form v-else ref="formRef" :model="editForm" :rules="formRules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-upload
            class="avatar-uploader"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="userName" label-width="100px">
            <el-input v-model="editForm.userName" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone" label-width="100px">
            <el-input v-model="editForm.phone" />
          </el-form-item>
          <el-form-item label="电子邮箱" prop="email" label-width="100px">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="所属专业" prop="major" label-width="100px">
            <el-input v-model="editForm.major" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="个人简介" prop="description" label-width="100px">
            <el-input
              v-model="editForm.description"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button v-if="!isViewMode" @click="handleClose">取消</el-button>
        <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
          保存
        </el-button>
        <el-button v-else type="primary" @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>
  
<script setup>
import { ref, reactive, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import apiClient from "@/axios";
const route = useRoute();
const router = useRouter();
import { Plus } from "@element-plus/icons-vue";

// 弹窗显示控制
const dialogVisible = ref(true);
//是否是查看模式
const isViewMode = computed(() => route.query.type === "details");

// 头像上传相关
const avatar = ref("");

const handleAvatarSuccess = (response, uploadFile) => {
  editForm.avatar.value = URL.createObjectURL(uploadFile.raw);
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

// 用户数据
const userInfo = ref({});
const editForm = reactive({
  userName: "",
  phone: null,
  email: null,
  major: null,
  description: null,
  avatar: null,
});

// 表单验证规则
const formRules = reactive({
  userName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确", trigger: "blur" },
  ],
  email: [{ type: "email", message: "邮箱格式不正确", trigger: "blur" }],
});

// 弹窗标题
const dialogTitle = computed(() =>
  isViewMode.value ? "用户信息详情" : "编辑用户信息"
);

// 加载用户数据
const loadUserData = async () => {
  try {
    const { data } = await apiClient.get(`/users/${route.query.id}`);
    Object.assign(userInfo.value, data.data);
    Object.keys(editForm).forEach((key) => {
      editForm[key] = data.data[key];
    });
    console.log(userInfo.value);
  } catch (error) {
    ElMessage.error("数据加载失败");
    handleClose();
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await apiClient.put(`/users/${route.query.id}`, editForm);
    ElMessage.success("修改成功");
    handleClose();
  } catch (error) {
    ElMessage.error("修改失败");
  }
};

// 关闭弹窗
const handleClose = () => {
  router.back();
};

// 监听路由变化
watch(
  () => route.query,
  (newVal) => {
    if (newVal.id) loadUserData();
  },
  { immediate: true }
);
</script>
  
<style scoped>
.el-descriptions {
  margin: 20px 0;
}

.el-form-item {
  margin-bottom: 22px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
}

.avatar-container .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}

.avatar-container .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 50%;
}
</style>
